package com.cykj.service.impl;

import com.cykj.dto.ResponseDTO;
import com.cykj.entity.AdminDO;
import com.cykj.mapper.AdminMapper;
import com.cykj.service.IAdminService;
import com.cykj.utils.JwtUtils;
import com.cykj.vo.AdminVO;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;


@Service
public class AdminServiceImpl implements IAdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public ResponseDTO login(AdminVO adminVO) {
        AdminDO login = adminMapper.login(adminVO);
        if (login == null) {
            return ResponseDTO.error("用户名或密码错误");
        }
        if (login.getStatus() == 0) {
            return ResponseDTO.error("用户被禁用");
        }
        // 封装生成 jwt
        HashMap<String, Object> claims = new HashMap<>();
        claims.put("adminId", login.getAdminId());          // 放入ID
        claims.put("nickname", login.getNickname());         // 放入昵称
        claims.put("roleId", login.getRoleId());             // 放入角色ID
        String jwt = JwtUtils.generateJwt(claims);          // 生成 jwt
        // jwt 存入 redis --> 有效期 30 分钟
        login.setPassword(null);   // 密码不存储在redis中
        redisTemplate.opsForValue().set(jwt, login, 30, TimeUnit.MINUTES);
        return ResponseDTO.success("登录成功", jwt);
    }

    @Override
    public ResponseDTO list(AdminVO adminVO) {
        List<AdminDO> list = adminMapper.list(adminVO);
        return !list.isEmpty()
                ? ResponseDTO.success("查询成功", list)
                : ResponseDTO.error("查询失败");
    }
}
